package com.maddox.relax.util;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.maddox.relax.PhotoPicker;

import java.io.File;

/**
 * 权限检查工具类
 */
public class PermissionUtils {

    /**
     * 校验拍照的权限
     */
    public static boolean hasCameraPermissions(FragmentActivity activity) {

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PhotoPicker.REQ_STORAGE);
                return false;
            }
        }

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.CAMERA}, PhotoPicker.REQ_CAMERA);
                return false;
            }

        }
        return true;
    }

    public static boolean hasStoragePermission(FragmentActivity activity) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PhotoPicker.REQ_STORAGE);
                return false;
            }
        }

        return true;
    }


    /**
     * 获取授权的Uri
     */
    public static Uri getUriForFile(@NonNull FragmentActivity activity, @NonNull File file) {

        Uri uri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            String authority = activity.getApplication().getPackageName() + ".fileprovider";
            uri = FileProvider.getUriForFile(activity, authority, file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }


}
